package com.card.hwatt.controllers;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.card.hwatt.assembler.*;
import com.card.hwatt.service.*;
import com.card.hwatt.dto.*;

/**
 * 维保单位用户
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserController extends BaseController{

	@Autowired
	@Qualifier("userService")
	private UserService userService;

	@Autowired
	@Qualifier("employeeService")
	private EmployeeService employeeService;

	@RequestMapping("/index")
	public String index() {
		return "user";
	}

	@RequestMapping("/save")
	public @ResponseBody
	ReturnValue save(Long id, boolean isAdmin) {
		com.card.hwatt.entity.Employee employee = employeeService.get(id);
		if (employee.user == null) {
			employee.user = new com.card.hwatt.entity.User();
			employee.user.id = UUID.randomUUID();
			employee.user.employee = employee;
			employee.user.isAdmin = isAdmin;
			userService.save(employee.user);
		} else {
			employee.user.isAdmin = isAdmin;
			userService.update(employee.user);
		}

		ReturnValue result = new ReturnValue();
		result.message = "ok";
		result.isSucess = true;
		return result;
	}

	@RequestMapping("/reset")
	public @ResponseBody
	ReturnValue reset(Long id) {
		com.card.hwatt.entity.Employee employee = employeeService.get(id);
		if (employee.user != null) {
			employee.user.password = null;
			userService.update(employee.user);
		}

		ReturnValue result = new ReturnValue();
		result.message = "ok";
		result.isSucess = true;
		return result;
	}

	@RequestMapping("/loadAll")
	public @ResponseBody
	PageResult<User> loadAll(Long id, String key) {
		PageResult<User> result = null;
		if (id == null) {
			result = new PageResult<User>();
			result.rows = new ArrayList<User>();
			return result;
		}
		List<Object> params = new ArrayList<Object>();

		params.add("%@" + id + "@%");

		if (StringUtils.isNotEmpty(key)) {
			params.add("%" + key + "%");
			params.add("%" + key + "%");
		}

		result = UserAssembler
				.convert(employeeService.loadAll(new PageParam(
						0,
						0,
						" department.path like ? "
								+ (StringUtils.isNotEmpty(key) ? " and ( name like ? or employeeCode like ? ) "
										: StringUtils.EMPTY), params,
						" employeeCode asc ")));

		return result;
	}
}
